package com.gec.mall.security.config;

import com.gec.mall.pojo.TbUser;
import com.gec.mall.security.component.RestAuthenticationEntryPoin;
import com.gec.mall.security.component.RestAuthorizationHandler;
import com.gec.mall.security.filter.JwtAuthenticationFilter;
import com.gec.mall.security.service.UserService;
import com.gec.mall.security.utils.UserDetailImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.ArrayList;
import java.util.Collection;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Autowired
    private UserService userService;

    @Bean
    public PasswordEncoder passwordEncoder(){   //配置加密算法
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService(){
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                System.out.println("认证账号 = " + username);
                TbUser user = userService.findUserByUsername(username);
                if (user!=null){
                    //权限列表
                    Collection<? extends GrantedAuthority> authorities = new ArrayList<>();
                    return new UserDetailImpl(user,authorities);
                }
                throw new UsernameNotFoundException("账号或密码错误！！！");
            }
        };
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()    //表示CrossOrigin解决跨域问题
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)     //无状态认证
                .and()
                .authorizeRequests()
                .antMatchers("/doLogin")
                .permitAll()    //doLogin资源不被拦截
                .anyRequest()
                .authenticated()    //除了前面的资源，其他都要认证
                .and()
                .addFilterBefore(new JwtAuthenticationFilter("/doLogin", authenticationManager()), UsernamePasswordAuthenticationFilter.class);     //添加用户认证过程的过滤器（用户登录）
                //.addFilterBefore(new JwtAuthorizationFilter(),UsernamePasswordAuthenticationFilter.class);    //资源的拦截认证过滤器，判断jwt的有效性

        http.csrf().disable();

        //报错的处理组件
        http.exceptionHandling().accessDeniedHandler(new RestAuthorizationHandler())
                                .authenticationEntryPoint(new RestAuthenticationEntryPoin());



    }
}
